/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.delivery;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.BaseActivity;
import cn.com.dhc.danlu.activity.delivery.order.MyOrdersActivity;
import cn.com.dhc.danlu.model.CreateOrderCashOnDeliveryModels;
import cn.com.dhc.danlu.util.ActivityUtils;
import cn.com.dhc.danlu.util.CalculatePriceUtil;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.holder.OrderReferSuccessItemHolder;
import cn.com.dhc.danlu.yijifu.IPayResultCallback;
import cn.com.dhc.danlu.yijifu.YjfPayEngine;

/**
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * author: 李一方(<a href="mailto:liyifang@danlu.com">liyifang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-17 11:02<br/>
 *
 * <p>
 * 成功提交多个订单
 * </p>
 */
public class OrderReferSuccessMultiActivity extends BaseActivity implements OnClickListener {
    /**
     * 倒计时异步识别码
     */
    private static final int COUNTDOWN_RESULT_CODE = 1;
    /**
     * 倒计时异步时间间隔
     */
    private static final int COUNTDOWN_INTERVAL = 1000;
    /**
     * 倒计时结束时间
     */
    private static final int COUNTDOWN_FINAL_TIME = 0;
    private static final int ALL_ORDER_TAB = 0;
    private static final int AWAIT_PAY_TAB = 1;
    /**
     * 支付回调处理
     */
    public IPayResultCallback ipayResultCallback = new IPayResultCallback() {

        // 支付处理中标识
        private boolean payExecIng = false;
        // 弹出支付dialog时，判断当前用户是否按了返回键的标志位
        private boolean isPressedCancel = false;

        @Override
        public void paySuccess() {
            //fix bug#1735 wuhaiyang
            int requestCode = !isPressedCancel ? MyOrdersActivity.ALL_INDEX : MyOrdersActivity.AWAIT_PAY_INDEX;
            MyOrdersActivity.startSelf(OrderReferSuccessMultiActivity.this, requestCode);
            isPressedCancel = false;
            setPayExecIng(false);
        }

        @Override
        public void payFail() {
            isPressedCancel = true;
            setPayExecIng(false);
        }

        @Override
        public void noPay() {
            isPressedCancel = true;
            setPayExecIng(false);
        }

        @Override
        public void paying() {
            setPayExecIng(true);
        }

        @Override
        public void payFinish() {
            setPayExecIng(false);
            finish();
        }

        @Override
        public void payError(int resInt) {
            ToastUtil.getInstance().show(resInt);
            setPayExecIng(false);
        }

        @Override
        public boolean getPayExecIng() {
            return payExecIng;
        }

        @Override
        public void setPayExecIng(boolean flag) {
            payExecIng = flag;
        }
    };
    /**
     * 货到付款订单
     */
    private LinearLayout llytOrdersOffline;
    /**
     * 在线支付订单
     */
    private LinearLayout llytOrdersONline;
    /**
     * 在线支付订单UI元素List
     */
    private List<OrderReferSuccessItemHolder> orderOnlineItemHolders;
    /**
     * 去支付
     **/
    private Button goPay;
    /**
     * 订单详情
     **/
    private Button goOrder;
    /**
     * 在线支付视图组
     **/
    private LinearLayout online;
    /**
     * 货到付款视图组
     **/
    private LinearLayout offline;
    /**
     * 完成
     */
    private TextView offlinePayway;
    private TextView tvAmount;
    /**
     * 倒计时支付时间5秒
     */
    private int countDownTimes = 5;
    /**
     * 易极付调用入口类
     */
    private YjfPayEngine yjfPaymentEntrance;
    /**
     * 丹露交易号
     */
    private String danluPaymentNo;
    /**
     * 接收在线支付数据
     */
    private ArrayList<CreateOrderCashOnDeliveryModels> ol = new ArrayList<>();
    /**
     * 统一处理handler事件
     */
    final Handler handler = new Handler() {

        @SuppressLint("SetTextI18n")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 获取handler支付倒计时标识
                case COUNTDOWN_RESULT_CODE:
                    if (countDownTimes > 0) {
                        countDownTimes--;
                        // 延时1s发送倒计时
                        Message message = handler.obtainMessage(COUNTDOWN_RESULT_CODE);
                        handler.sendMessageDelayed(message, COUNTDOWN_INTERVAL);
                    } else {
                        // 移除handler支付倒计时标识
                        handler.removeMessages(COUNTDOWN_RESULT_CODE);
                        if (ol != null && ol.size() == 1) {
                            // 去支付
                            execOnlinePay();
                        } else {
                            goOrdersGroup();
                        }
                    }
                    break;

                default:
                    break;
            }

            super.handleMessage(msg);
        }
    };
    private boolean isZeroOrder = false;
    private boolean isAllowOnlinePay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_refer_success_multi);

        // 易极付调用入口类实例化
        yjfPaymentEntrance = new YjfPayEngine(this, ipayResultCallback, false);
        initView();
        init();
    }

    @Override
    protected String getActivityTitle() {
        return null;
    }

    @Override
    protected void back() {
        handler.removeMessages(COUNTDOWN_RESULT_CODE);
        // 返回前画面
        ActivityUtils.startMainMenuActivity(this);
        this.finish();
    }

    /**
     * 页面初始化
     */
    private void init() {
        Intent intent = new Intent(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_ACTION);
        sendBroadcast(intent);
        // 接收货到付款订单数据
        ArrayList<CreateOrderCashOnDeliveryModels> ms = getIntent().getParcelableArrayListExtra("CMS");
        // 接收在线支付数据
        ol = getIntent().getParcelableArrayListExtra("ONLINE");

        isZeroOrder = getIntent().getBooleanExtra("isZero", false);

        if (isZeroOrder) {
            //零元订单
            online.setVisibility(View.GONE);
            offline.setVisibility(View.VISIBLE);
            offlinePayway.setText("支付方式：在线支付");
            tvAmount.setVisibility(View.GONE);
            attachView();
            goOrder.setOnClickListener(this);
        } else {
            // 货到付款拆单为listview提供adapter
            if (ms != null && ms.size() > 0) {
                offline.setVisibility(View.VISIBLE);
                buildOrderOfflineList(ms);
            } else {
                offline.setVisibility(View.GONE);
            }
            // 在线支付直接渲染页面数据
            if (ol != null && ol.size() > 0) {
                buildOrderOnlineList(ol);
                CreateOrderCashOnDeliveryModels models = ol.get(0);
                danluPaymentNo = models.getPaymentNo();
                online.setVisibility(View.VISIBLE);
                int compare = CalculatePriceUtil.compare(models.getPrice(), "0");
                if (compare == 0 || compare == -1) {
                    // 促销相关导致零元订单
                    goPay.setText("查看订单");
                    isAllowOnlinePay = false;
                } else {
                    isAllowOnlinePay = true;
                }
            } else {
                online.setVisibility(View.GONE);
            }
            goPay.setOnClickListener(this);
            goOrder.setOnClickListener(this);
        }

    }

    private void initView() {
        llytOrdersOffline = (LinearLayout) findViewById(R.id.llytOrdersOffline);
        llytOrdersONline = (LinearLayout) findViewById(R.id.llytOrdersONline);
        goPay = (Button) findViewById(R.id.goPay);
        goOrder = (Button) findViewById(R.id.goOrder);
        online = (LinearLayout) findViewById(R.id.online);
        offline = (LinearLayout) findViewById(R.id.offline);
        offlinePayway = (TextView) findViewById(R.id.offline_payway);
        tvAmount = (TextView) findViewById(R.id.tv_amount);
        llytBack = (LinearLayout) findViewById(R.id.llytBack);
    }

    private void attachView() {
        buildOrderOfflineList(ol);
    }

    /**
     * 倒计时支付
     */
    private void paymentCountDown() {
        Message message = handler.obtainMessage(COUNTDOWN_RESULT_CODE);
        handler.sendMessageDelayed(message, COUNTDOWN_INTERVAL);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.goPay:
                if (isAllowOnlinePay) {
                    if (countDownTimes > 0) {
                        // 倒计时支付时间清空
                        countDownTimes = COUNTDOWN_FINAL_TIME;
                        // 移除handler支付倒计时标识
                        handler.removeMessages(COUNTDOWN_RESULT_CODE);
                    }
                    if (ol != null && ol.size() == 1) {
                        // 去支付
                        execOnlinePay();
                    } else {
                        goOrdersGroup();
                    }
                } else {
                    goOrdersGroup();
                }
                break;

            case R.id.goOrder:
                handler.removeMessages(COUNTDOWN_RESULT_CODE);
                if (isZeroOrder) {
                    //待付款
                    MyOrdersActivity.startSelf(this, MyOrdersActivity.AWAIT_PAY_INDEX);
                } else {
                    MyOrdersActivity.startSelf(this, MyOrdersActivity.ALL_INDEX);
                }
                this.finish();
                break;

            default:
                break;
        }
    }

    /**
     * 执行易极付支付
     */
    private void execOnlinePay() {
        yjfPaymentEntrance.payAction(danluPaymentNo);
    }

    /**
     * 跳转至订单列表
     */
    private void goOrdersGroup() {
        //fix #1735 bug  --- wuhaiyang modify
        MyOrdersActivity.startSelf(this, MyOrdersActivity.AWAIT_PAY_INDEX);
        this.finish();
    }

    /**
     * get OrderReferSuccessItemHolder by spec view container
     */
    private OrderReferSuccessItemHolder findStoreItemView(View convertView) {
        OrderReferSuccessItemHolder holder = new OrderReferSuccessItemHolder();
        holder.orderNO = (TextView) convertView.findViewById(R.id.ordersSuccessNum);
        holder.orderPrice = (TextView) convertView.findViewById(R.id.ordersSuccessPrice);
        return holder;
    }

    /**
     * 构建在线支付订单列表
     */
    private void buildOrderOnlineList(ArrayList<CreateOrderCashOnDeliveryModels> ol) {
        llytOrdersONline.removeAllViews();
        if (orderOnlineItemHolders == null) {
            orderOnlineItemHolders = new ArrayList<>();
        } else {
            orderOnlineItemHolders.clear();
        }
        final int olSize = ol.size();
        for (int i = 0; i < olSize; i++) {
            // 实例在线支付订单列表item视图
            final View convertStoreView = LayoutInflater.from(this).inflate(R.layout.layout_refer_orders_success_item, null);
            final OrderReferSuccessItemHolder itemHolder = findStoreItemView(convertStoreView);
            String paymentNo = ol.get(i).getPaymentNo();
            String payPrice = ol.get(i).getPrice();
            // 将价格分换成元
            BigDecimal price = new BigDecimal(payPrice);
            itemHolder.orderNO.setText(paymentNo);
            itemHolder.orderPrice.setText(String.valueOf(CommonUtils.fenToYuan(price)));
            orderOnlineItemHolders.add(itemHolder);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, 0, 5);
            llytOrdersONline.addView(convertStoreView, lp);
        }
    }

    /**
     * 构建货到付款订单列表
     */
    private void buildOrderOfflineList(ArrayList<CreateOrderCashOnDeliveryModels> ordersoffline) {
        llytOrdersOffline.removeAllViews();
        if (orderOnlineItemHolders == null) {
            orderOnlineItemHolders = new ArrayList<>();
        } else {
            orderOnlineItemHolders.clear();
        }
        final int ordersofflineSize = ordersoffline.size();
        for (int i = 0; i < ordersofflineSize; i++) {
            // 实例在线支付订单列表item视图
            final View convertStoreView = LayoutInflater.from(this).inflate(R.layout.layout_refer_orders_success_item, null);
            final OrderReferSuccessItemHolder itemHolder = findStoreItemView(convertStoreView);
            String paymentNo = ordersoffline.get(i).getPaymentNo();
            String payPrice = ordersoffline.get(i).getPrice();
            // 将价格分换成元
            BigDecimal price = new BigDecimal(payPrice);
            itemHolder.orderNO.setText(paymentNo);
            itemHolder.orderPrice.setText(String.valueOf(CommonUtils.fenToYuan(price)));
            orderOnlineItemHolders.add(itemHolder);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, 0, 0, 5);
            llytOrdersOffline.addView(convertStoreView, lp);
        }
    }

    @Override
    public void onBackPressed() {
        this.finish();
        handler.removeMessages(COUNTDOWN_RESULT_CODE);
        super.onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (YjfPayEngine.YIJIFU_PAYYMENT_CODE == requestCode) {
            // 处理支付结果
            yjfPaymentEntrance.handlerPayResult(requestCode, resultCode, data);
        }
        if (YjfPayEngine.YIJIFU_REGISTER_CODE == requestCode) {
            boolean registerSuccessFlag = false;
            if (data != null) {
                registerSuccessFlag = data.getBooleanExtra(CommonConst.BroadcastAction.BROADCAST_GET_YJF_REGISTER_ACTION, false);
            }
            // 处理注册结果
            if (registerSuccessFlag) {
                yjfPaymentEntrance.handlerPayResult(requestCode, resultCode, data);
                finishActivity(YjfPayEngine.YIJIFU_REGISTER_CODE);
            } else {
                finishActivity(YjfPayEngine.YIJIFU_REGISTER_CODE);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
